package com.gomore.opple.service.impl;

import android.util.Log;

import com.gomore.opple.BuildConfig;
import com.gomore.opple.service.UploadProcessor;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

/**
 * Created by asus on 2017/5/19.
 */
public class ServerUploadProcessor implements UploadProcessor {
    private static final int TIME_OUT = 10 * 10000000; //超时时间
    private static final String CHARSET = "utf-8"; //设置编码

    @Override
    public void upload(String localUrl) {
        String url = BuildConfig.HOST + "system/upload";
        File file = new File(localUrl);
        if (file.exists()) {
            //第一次连接，返回session id
            String sessionId = testUrlConnection(url);
            //第二次使用session id连接
            uploadFile(file, url, sessionId);
        }
    }

    /**
     * android上传文件到服务器
     *
     * @param file       需要上传的文件
     * @param RequestURL 请求的rul
     * @return 返回响应的内容
     */
    public void uploadFile(File file, String RequestURL, String sessionId) {
        String end = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
        String newName = "image.jpg";
        try {
            URL url = new URL(RequestURL);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            /* 允许Input、Output，不使用Cache */
            con.setDoInput(true);
            con.setDoOutput(true);
            con.setUseCaches(false);
            /* 设置传送的method=POST */
            con.setRequestMethod("POST");
            /* setRequestProperty */
            con.setRequestProperty("Connection", "Keep-Alive");
            con.setRequestProperty("Cookie", sessionId);
            con.setRequestProperty("Charset", "UTF-8");
            con.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
            /* 设置DataOutputStream */
            DataOutputStream ds = new DataOutputStream(con.getOutputStream());
            ds.writeBytes(twoHyphens + boundary + end);
            ds.writeBytes("Content-Disposition: form-data; "
                    + "name=\"file1\";filename=\"" + newName + "\"" + end);
            ds.writeBytes(end);
            /* 取得文件的FileInputStream */
            FileInputStream fStream = new FileInputStream(file);
            /* 设置每次写入1024bytes */
            int bufferSize = 1024;
            byte[] buffer = new byte[bufferSize];
            int length = -1;
            /* 从文件读取数据至缓冲区 */
            while ((length = fStream.read(buffer)) != -1) {
                /* 将资料写入DataOutputStream中 */
                ds.write(buffer, 0, length);
            }
            ds.writeBytes(end);
            ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
            /* close streams */
            fStream.close();
            ds.flush();
            /* 取得Response内容 */
            InputStream is = con.getInputStream();
            int ch;
            StringBuffer b = new StringBuffer();
            while ((ch = is.read()) != -1) {
                b.append((char) ch);
            }
            /* 将Response显示于Dialog */
            Log.e("231235r234", "" + con.getResponseCode());
            Log.e("231235r234", "" + b.toString());
            /* 关闭DataOutputStream */
            ds.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String testUrlConnection(String RequestURL) {
        OutputStream out = null;
        InputStream in = null;
        try {
            URL url = new URL(RequestURL);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setRequestMethod("POST");
            //打印请求头信息
            Map hfs = con.getHeaderFields();
            Set<String> keys = hfs.keySet();
            for (String str : keys) {
                List<String> vs = (List) hfs.get(str);
                System.out.print(str + ":");
                for (String v : vs) {
                    System.out.print(v + "\t");
                }
                System.out.println();
            }
            System.out.println("-----------------------");
            String cookieValue = con.getHeaderField("Set-Cookie");
            System.out.println("cookie value:" + cookieValue);
            String sessionId = cookieValue.substring(0, cookieValue.indexOf(";"));
            return sessionId;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                if (in != null)
                    in.close();
                if (out != null)
                    out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
